"Les cours de neeko.fr"

Retour en haut

Design Pattern : Le Singleton

Une classe avec une seule instance.

Intention

"Garantit qu'une classe n'a qu'une seule instance et fournit un point d'accès de type global à cette classe."

-- Design Pattern: Catalogue de modèles de conception réutilisables.

Utilisation

Exemple d'implémentation

Le principe

Pour accéder à l'instance, on aura donc pas d'autre choix que d'appeller la méthode statique : getInstance()

Le code

public class MonSingleton { static private MonSingleton instance; static public MonSingleton getInstance(){ if (instance == null){ instance = new MonSingleton(); } return instance; } private MonSingleton(){ } }

Utilisation

//impossible d'instancier avec new MonSingleton instance = new MonSingleton();

//le seul moyen est d'appeller la méhode statique MonSingleton instance = MonSingleton.getInstance();

Exemple plus complet

Bien sur, il est possible d'ajouter des propriétés et des méthodes public au singleton !

public class MonSingleton { static private MonSingleton instance; public String message; public String user; static public MonSingleton getInstance(){ if (instance == null){ instance = new MonSingleton(); } return instance; } private MonSingleton(){ this.message = "Bonjour"; this.user = "Boby"; } public void hello(){ System.out.println( this.message + " " + this.user); } }

Utilisation

MonSingleton instance = MonSingleton.getInstance(); instance.hello(); //affiche "Bonjour Boby"

MonSingleton.getInstance().hello(); //affiche "Bonjour Boby"

//on peut modifier l'instance MonSingleton instance2 = MonSingleton.getInstance(); instance2.user = "Robert Smith"; instance2.message = "Hi!";

MonSingleton instance3 = MonSingleton.getInstance(); instance3.hello(); //affiche "Hi! Robert Smith"

MonSingleton.getInstance().hello(); //affiche "Hi! Robert Smith"